<template>
  <div class="panel">

    <el-form v-loading="!operateData.dataReady || operateData.isLoading" ref="formRef" :rules="formRules" :model="operateData.post" class="demo-form-inline" label-width="100px">

      <el-form-item label="标题" prop="title">
        <el-input v-model="operateData.post.title" show-word-limit maxlength="20" style="max-width:420px;" placeholder="输入推送标题，最多20个字"></el-input>
      </el-form-item>

      <el-form-item label="正文" prop="text">
        <el-input v-model="operateData.post.text" show-word-limit type="textarea" maxlength="140" :rows="3" placeholder="输入推送正文，最多140个字"></el-input>
      </el-form-item>

      <el-form-item label="配图" prop="imageUrl">
        <upload-oss list-type="picture-card" :limit="1" :imageUrl="operateData.imageUrlList" :beforeUpload="(file)=>operateFn.beforeUpload(file)" @upload="operateFn.afterUpload"></upload-oss>
      </el-form-item>

      <el-form-item label="链接" prop="url">
        <el-input v-model="operateData.post.url"></el-input>
      </el-form-item>

      <el-form-item label="链接目标">
        <el-select v-model="operateData.post.jump" placeholder="">
          <el-option v-for="(item,index) in operateData.targetList" :key="index" :label="item.value" :value="item.key" />
        </el-select>
      </el-form-item>

      <el-form-item label="推送类型">
        <el-radio-group v-model="operateData.post.type">
          <el-radio :label="1" size="large">实时推送</el-radio>
          <el-radio :label="0" size="large">定时推送</el-radio>
        </el-radio-group>
        <!-- <el-date-picker v-if="operateData.post.type===0" v-model="operateData.post.sendAt" type="datetime" placeholder="选择时间" :disabledDate="operateFn.disabledDate" @change="operateFn.checkDateTime"/> -->

        <el-form-item v-if="operateData.post.type===0" prop="sendAt" style="display:inline-block;margin-left:24px;">
          <el-date-picker v-model="operateData.post.sendAt" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="选择时间" :disabledDate="operateFn.disabledDate" @change="operateFn.checkDateTime(operateData.post.sendAt)" />
        </el-form-item>
      </el-form-item>

      <el-form-item label="是否push">
        <el-switch v-model="operateData.post.isPush" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>

      <el-form-item label="推送对象">
        <el-radio-group v-model="operateData.post.isAll">
          <el-radio :label="0" size="large">所有已注册用户</el-radio>
          <el-radio :label="1" size="large">选定用户</el-radio>
        </el-radio-group>
        <template v-if="operateData.post.isAll===1">
          <div style="display:block;margin-bottom:12px;">
            <uploadAnalysis cancel-upload @onStep="operateFn.uploadAnalysisStep" text="导入列表文件"></uploadAnalysis>
            <span style="color: rgb(167 167 167);margin-left: 24px;vertical-align: middle;">文件表头需含有“id”或“phone”或“nickName”项，否则无法识别</span>
          </div>

          <el-form-item style="display:block;margin-bottom:12px;" prop="userList">
            <el-input v-model="operateData.post.userList" type="textarea" :placeholder="`请输入用户${['id','昵称','手机号'][operateData.post.userType]}，用 “；”（中文分号） 隔开`" :rows="10"></el-input>
            <p class="isHint">{{`各项数据之间，用 “；”（中文分号） 隔开`}}</p>
          </el-form-item>

          <el-radio-group v-model="operateData.post.userType">
            <el-radio :label="0" size="large">ID（id）</el-radio>
            <el-radio :label="1" size="large">昵称（nickName）</el-radio>
            <el-radio :label="2" size="large">手机号（phone）</el-radio>
          </el-radio-group>
        </template>
      </el-form-item>

      <el-form-item style="text-align:center">
        <el-button type="primary" plain @click="operateFn.submitPre(formRef)">提交</el-button>
      </el-form-item>
    </el-form>

  </div>

</template>

<script setup>
import { ref, reactive, watchEffect } from "vue";
import {
  getPullMessageDetail,
  addPullMessage,
  editPullMessage,
  getLinkTarget,
} from "@/api/operation.js";
import { onBeforeRouteUpdate, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useStore } from "@/store";

import uploadAnalysis from "@/components/UploadExcel/uploadAnalysis";
import UploadOss from "@/components/AliOSS";
const store = useStore();

const router = useRouter();
const params = ref({});
const query = ref({});
watchEffect(()=>{
  console.log("router params:",router.currentRoute.value.params)
  params.value = router.currentRoute.value.params;
})
watchEffect(()=>{
  query.value = router.currentRoute.value.query;
})

const formRef = ref();

const formRules = reactive({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  text: [{ message: "请输入正文", trigger: "blur" }],
  imageUrl: [{ message: "请上传配图", trigger: "change" }],
  sendAt: [{ required: true, message: "请选择发送时间", trigger: "change" }],
  url: [{ message: "请输入链接", trigger: "blur" }],
  userList: [
    { required: true, message: "请输入用户内容", trigger: ["change", "blur"] },
  ],
});

// 新增和编辑
const { $data: operateData, $fn: operateFn } = (() => {
  const backup = {
    header: ["id", "nickName", "phone"], //顺序为优先级
    post: {
      // id: "",
      title: "", //标题	是	[string]		查看
      text: "", //正文	是	[string]		查看
      imageUrl: "", //图片地址	是	[string]		查看
      url: "", //链接地址	是	[string]		查看
      sendAt: "", //发送时间	是	[string]		查看
      type: 0, //发送类型 0、不定时；1、定时	是	[string]		查看
      isPush: 0, //是否推送极光 0、不推送；1、推送	是	[string]		查看
      isAll: 0, //是否全部用户。0、是全部；1、部分用户	是	[string]		查看
      userList: "", //用户列表	是	[string]		查看
      userType: 0, //用户类型。0、id；1、昵称；2、电话 	是	[string]		查看
      jump: 8,
    },
    fileData: [],
  };
  const $data = reactive({
    isEdit: query.value.type === "edit",
    post: {
      ...backup.post,
    },
    isLoading: false,//正在上传数据？
    detail: {},
    dataReady: false,

    imageUrlList: undefined,
    uploadUserNum: 0, //上传的数据数量
    analysisUserNum: 0, //解析后的数据数量（已去重）

    targetList: [],
  });

  const $fn = {
    resetData(){
      $data.detail = {};
      $data.post = {...backup.post};
      $data.imageUrlList = undefined;
    },
    getDetails() {
      $data.dataReady = false;
      getPullMessageDetail(params.value.id).then((res) => {
        console.log(params.value.id, "detail res:", res);
        if (res.code === 0) {
          $data.dataReady = true;
          $data.detail = { ...res.data };
          let keys= Object.keys(backup.post);
          for(let key of keys){
            if(key === "imageUrl"){
              $data.imageUrlList = [{url:$data.detail[key]}]
            }
            if(key === "userList"){
              $data.post[key] = $data.detail[key].join("；");
            }else{
              $data.post[key] = $data.detail[key] || backup.post[key];
            }
            
          }
        }
      });
    },
    getTargetList(){
      getLinkTarget().then(res=>{
        if(res.code===0){
          $data.targetList = res.data||[];
        }
      })
    },
    submitPre(formRef) {
      if (!formRef) return;
      formRef.validate((valid) => {
        if (valid) {
          $fn.submitData();
        }
      });
    },
    submitData() {
      // 数据验证
      let req = {
        ...$data.post,
        userList: (() => {
          if ($data.post.isAll !== 1) {
            return [];
          }
          let list = new Set();
          for (let prop of $data.post.userList.split(/[;；]/) || []) {
            if(!prop)continue;
            list.add(prop);
          }
          return [...list];
        })(),
      };
      $data.isLoading = true;
      if ($data.isEdit) {
        editPullMessage({...req,id:params.value.id}).then((res) => {
          if (res.code === 0) {
            ElMessage.success("修改成功！");
            store.dispatch("tagsView/delView", { ...router.currentRoute.value }).then(() => {
              router.replace({ path: "/operation/messagePull" });
            });
          }
          $data.isLoading = false;
        });
      } else {
        addPullMessage(req).then((res) => {
          if (res.code === 0) {
            ElMessage.success("添加成功！");
            store.dispatch("tagsView/delView", { ...router.currentRoute.value }).then(() => {
              router.replace({ path: "/operation/messagePull" });
            });
          }
          $data.isLoading = false;
        });
      }
    },
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        const size = file.size / 1024;
        if (size > 1024) {
          ElMessage.error("图片大小不能超过 1 MB！");
          reject();
          return;
        }
        resolve();
      });
    },
    afterUpload(list) {
      const url = list[0];
      if (!url) {
        $data.post.imageUrl = "";
        $data.imageUrlList = undefined;
        return;
      }
      $data.post.imageUrl = "https://img.qumoyugo.com" + url.showUrl;
      $data.imageUrlList = [{ url: $data.post.imageUrl }];
    },

    // 发送时间限制
    disabledDate: (time) => {
      return time.getTime() < Date.now() - 8.64e7;
    },
    checkDateTime(time) {
      if(!time)return;
      if (new Date(time).getTime() < Date.now()) {
        $data.post.sendAt = "";
        ElMessage.warning("发送时间不能小于当前时间！");
      }
    },

    uploadAnalysisStep(step, res) {
      if (step === "analysisSuccess") {
        $data.uploadUserNum = (res.results || []).length;
        backup.fileData = res.results;
        let keyName = "";
        for (let key of backup.header) {
          if (res.header.includes(key)) {
            ElMessage.success("解析成功！");
            keyName = key;
            $data.post.userType = { id: 0, phone: 2, nickName: 1 }[keyName];
            break;
          }
        }
        if (!keyName) {
          ElMessage.warning("数据项不存在，请检查上传文件！");
          return;
        }
        let list = new Set();
        for (let i = 0; i < $data.uploadUserNum; i++) {
          let prop = res.results[i];
          if (prop[keyName]) {
            list.add(prop[keyName]);
          }
        }
        $data.analysisUserNum = list.size;
        $data.post.userList = [...list].join("；");
      } else if (step === "analysisFail") {
        ElMessage.error("文件解析失败！");
      }
    },
  };

  return {
    $data,
    $fn,
  };
})();

function init(){
  operateFn.resetData();
  if (operateData.isEdit) {
    operateFn.getDetails();
  } else {
    operateData.dataReady = true;
  }
  operateFn.getTargetList();
}
init();


// 从相同路由进入（不同参数），如/a/b/1 => /a/b/2
onBeforeRouteUpdate((to, from, next) => {
  if(!to.params.id){
    operateData.isEdit = false;
  }else{
    operateData.isEdit = true;
    params.value.id = to.params.id;
  }
  init();
  next();
});

</script>

<style scoped lang="scss">
.panel {
  background-color: #ffffff;
  padding: 12px;
  border-radius: 8px;
}
.isEmpty {
  color: rgb(172, 172, 172);
}
.isHint {
  color: rgb(71, 71, 71);
}
</style>